#include "QDServices.h"

int QDServices::UpLoad(int cli, QDReqParams *info){

    NetFileIO netFile(cli, info->blockSize);

    FileIO localFile(info->user, info->path, info->name, info->blockSize, info->size);
    localFile.Open("w");

    char buff[8192];
    // 简化成普通读写操作
    while(1){
        memset(buff, 0 ,sizeof(buff));

        // 读取 buff
        int rSize = netFile.Read(buff);

        if(rSize <= 0){
            break;
        }

        // 写入buff
        localFile.Write(buff, rSize);

    }

    return 0;
}

int QDServices::DownLoad(int cli, QDReqParams *info){

    NetFileIO netFile(cli, info->blockSize);

    FileIO localFile(info->user, info->path, info->name, info->blockSize, info->size);
  
    localFile.Open("r");

    char buff[8192];

    int rSize = 0;

    while(1){
        rSize = localFile.Read(buff, localFile.getBlockSize());

        netFile.Write(buff, rSize);

        if(rSize <= 0){
            break;
        }
    }

    return 0;
}

int QDServices::Request(int cli){

        QDReqParams cliParams;
        memset(&cliParams, 0 , sizeof(cliParams)); // 

        recv(cli, &cliParams, sizeof(QDReqParams), 0);

        // 返回给 客户端 block 参数, 客户端按顺序发送文件数据
        cliParams.blockSize = 4096;            // 根据网络波动, 设置最合适的传输速率

        // 将更新后的信息返回给客户端
        send(cli, &cliParams, sizeof(QDReqParams), 0);

        if( cliParams.mode == OP_UPLOAD){
            QD_LOGD("%s:upload:%s%s", cliParams.user, cliParams.path, cliParams.name);

            // 开始上传
            UpLoad(cli, &cliParams);
        }
        else if(cliParams.mode == OP_DOWNLOAD){
            QD_LOGD("%s:download:%s%s", cliParams.user, cliParams.path, cliParams.name);
            
            DownLoad(cli, &cliParams);
        } 
        else{
            QD_LOGD("No Any Select");
        }

    return 0;
}
